package com.xander.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Xander on 2018-06-14.
 */
public class ConnectionUtils {
    public static String httpUrlConnection(JSONObject jsonObject, String urls, String method) {
        StringBuffer sb = new StringBuffer();
        int httpcode = 0;
        try {
            URL url = new URL(urls);
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置http连接属性
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestMethod(method);
            // 转换为字节数组
            byte[] data = (jsonObject.toString()).getBytes();
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置接收数据的格式
            conn.setRequestProperty("Accept", "application/json");
            // 设置发送数据的格式
            conn.setRequestProperty("Content-Type", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write((jsonObject.toString()).getBytes());
            out.flush();
            out.close();
            //http状态码
            httpcode = conn.getResponseCode();
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine = new String();
                    BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
                    while ((readLine = responseReader.readLine()) != null) {
                        sb.append(readLine).append("\n");
                    }
                    responseReader.close();
                    return sb.toString();
                } catch (Exception e1) {
                    return "readerror";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(httpcode);
    }
}
